/**
 * 模型状态指示器 - 实时显示模型健康状态
 */
import React, { useState, useEffect } from 'react';
import { Badge, Tooltip, Button, Space, Spin, Alert } from 'antd';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  SyncOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import modelDiscoveryService, { AvailableModel } from '@/services/model-discovery.service';
import { useModelDiscoveryStore } from '@/stores/model-discovery.store';
import './style.css';

interface ModelStatusIndicatorProps {
  modelId: string;
  showDetails?: boolean;
  size?: 'small' | 'default' | 'large';
  onStatusChange?: (status: string) => void;
}

const ModelStatusIndicator: React.FC<ModelStatusIndicatorProps> = ({
  modelId,
  showDetails = false,
  size = 'default',
  onStatusChange
}) => {
  const [model, setModel] = useState<AvailableModel | null>(null);
  const [checking, setChecking] = useState(false);
  const [lastCheck, setLastCheck] = useState<Date | null>(null);
  
  const { availableModels, updateModelStatus } = useModelDiscoveryStore();
  
  // 获取模型信息
  useEffect(() => {
    const foundModel = availableModels.find(m => m.id === modelId);
    if (foundModel) {
      setModel(foundModel);
      if (foundModel.lastChecked) {
        setLastCheck(foundModel.lastChecked);
      }
    }
  }, [modelId, availableModels]);
  
  // 状态变化回调
  useEffect(() => {
    if (model && onStatusChange) {
      onStatusChange(model.status);
    }
  }, [model?.status, onStatusChange]);
  
  // 手动检查健康状态
  const handleCheck = async () => {
    if (!model || checking) return;
    
    setChecking(true);
    updateModelStatus(modelId, 'checking');
    
    try {
      const health = await modelDiscoveryService.checkModelHealth(modelId);
      const newStatus = health.status === 'available' ? 'available' : 'unavailable';
      
      updateModelStatus(modelId, newStatus);
      setLastCheck(new Date());
      
      // 更新本地状态
      setModel(prev => prev ? {
        ...prev,
        status: newStatus,
        lastChecked: new Date(),
        responseTime: health.responseTime,
        errorMessage: health.error
      } : null);
      
    } catch (error) {
      updateModelStatus(modelId, 'unavailable');
      setModel(prev => prev ? {
        ...prev,
        status: 'unavailable',
        errorMessage: error instanceof Error ? error.message : '检查失败'
      } : null);
    } finally {
      setChecking(false);
    }
  };
  
  // 获取状态图标和颜色
  const getStatusIcon = () => {
    if (checking) {
      return <SyncOutlined spin />;
    }
    
    switch (model?.status) {
      case 'available':
        return <CheckCircleOutlined style={{ color: '#52c41a' }} />;
      case 'unavailable':
        return <CloseCircleOutlined style={{ color: '#f5222d' }} />;
      case 'checking':
        return <SyncOutlined spin style={{ color: '#faad14' }} />;
      default:
        return <ExclamationCircleOutlined style={{ color: '#d9d9d9' }} />;
    }
  };
  
  const getStatusText = () => {
    if (checking) return '检查中...';
    
    switch (model?.status) {
      case 'available':
        return '在线';
      case 'unavailable':
        return '离线';
      case 'checking':
        return '检查中';
      default:
        return '未知';
    }
  };
  
  const getStatusColor = () => {
    if (checking) return 'processing';
    
    switch (model?.status) {
      case 'available':
        return 'success';
      case 'unavailable':
        return 'error';
      case 'checking':
        return 'processing';
      default:
        return 'default';
    }
  };
  
  if (!model) {
    return <Badge status="default" text="未知模型" />;
  }
  
  const statusBadge = (
    <Badge 
      status={getStatusColor()}
      text={showDetails ? getStatusText() : undefined}
      size={size}
    />
  );
  
  if (!showDetails) {
    return (
      <Tooltip
        title={
          <div>
            <div>状态: {getStatusText()}</div>
            {model.responseTime && (
              <div>响应时间: {model.responseTime}ms</div>
            )}
            {model.errorMessage && (
              <div>错误: {model.errorMessage}</div>
            )}
            {lastCheck && (
              <div>上次检查: {lastCheck.toLocaleTimeString()}</div>
            )}
          </div>
        }
      >
        {statusBadge}
      </Tooltip>
    );
  }
  
  return (
    <div className="model-status-indicator">
      <Space>
        {statusBadge}
        
        {model.responseTime && model.status === 'available' && (
          <Tooltip title="响应时间">
            <Space size={4}>
              <ThunderboltOutlined 
                style={{ 
                  color: model.responseTime < 500 ? '#52c41a' : 
                         model.responseTime < 1000 ? '#faad14' : '#f5222d' 
                }} 
              />
              <span style={{ fontSize: '12px' }}>{model.responseTime}ms</span>
            </Space>
          </Tooltip>
        )}
        
        <Button
          type="text"
          size="small"
          icon={checking ? <Spin size="small" /> : <SyncOutlined />}
          onClick={handleCheck}
          disabled={checking}
          title="检查状态"
        >
          {checking ? '检查中' : '检查'}
        </Button>
      </Space>
      
      {model.status === 'unavailable' && model.errorMessage && (
        <Alert
          message={model.errorMessage}
          type="error"
          size="small"
          style={{ marginTop: 8 }}
          showIcon
        />
      )}
      
      {lastCheck && (
        <div style={{ fontSize: '12px', color: '#999', marginTop: 4 }}>
          上次检查: {lastCheck.toLocaleTimeString()}
        </div>
      )}
    </div>
  );
};

export default ModelStatusIndicator;